#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
手动触发缩容脚本
用于在低负载情况下手动触发缩容
"""

import requests
import time
import json

def manual_scale_in():
    """手动触发缩容"""
    base_url = "http://localhost:8080"
    
    print("🔍 手动触发缩容测试")
    print("=" * 50)
    
    # 1. 检查当前状态
    print("📊 当前系统状态:")
    try:
        # 获取服务器列表
        servers_response = requests.get(f"{base_url}/api/v1/servers", timeout=10)
        if servers_response.status_code == 200:
            servers_data = servers_response.json()
            if servers_data.get("success"):
                servers_list = servers_data["data"]
                actual_server_count = len(servers_list)
                print(f"  实际服务器数量: {actual_server_count}")
            else:
                print(f"❌ 获取服务器列表失败: {servers_data.get('error')}")
                return
        else:
            print(f"❌ 获取服务器列表请求失败: {servers_response.status_code}")
            return
            
        # 获取系统状态
        response = requests.get(f"{base_url}/api/v1/system/status", timeout=10)
        if response.status_code == 200:
            data = response.json()
            queue = data["data"]["queue"]
            scaling = data["data"]["scaling"]
            
            print(f"  系统显示服务器数量: {data['data']['servers']['servers']['total']}")
            print(f"  队列长度: {queue['total_tasks_in_queue']}")
            print(f"  平均响应时间: {scaling['latest_metrics']['average_response_time']:.2f}秒")
            print(f"  CPU利用率: {scaling['latest_metrics']['cpu_utilization']:.1f}%")
            print(f"  最小服务器数: {scaling['scaling_config']['min_servers']}")
            
            if actual_server_count <= scaling['scaling_config']['min_servers']:
                print("❌ 当前服务器数量已达到最小值，无法缩容")
                return
                
        else:
            print(f"❌ 获取系统状态失败: {response.status_code}")
            return
    except Exception as e:
        print(f"❌ 请求失败: {e}")
        return
    
    # 2. 显示缩容条件
    print(f"\n📝 缩容触发条件:")
    print(f"  - 平均响应时间 < 1秒")
    print(f"  - 队列积压 < 3个任务") 
    print(f"  - CPU利用率 < 30%")
    print(f"  - 低负载状态持续 > 5分钟")
    print(f"  - 需要满足至少2个条件")
    print(f"  - 最小服务器数限制: {scaling['scaling_config']['min_servers']}")
    
    # 3. 检查当前是否满足缩容条件
    current_metrics = scaling['latest_metrics']
    conditions_met = []
    
    if current_metrics['average_response_time'] < 1.0:
        conditions_met.append("响应时间 < 1秒")
    
    if current_metrics['queue_backlog'] < 3:
        conditions_met.append("队列 < 3个任务")
    
    if current_metrics['cpu_utilization'] < 30.0:
        conditions_met.append("CPU利用率 < 30%")
    
    print(f"\n✅ 当前满足的条件: {len(conditions_met)}/3")
    for condition in conditions_met:
        print(f"  - {condition}")
    
    if len(conditions_met) < 2:
        print("❌ 不满足缩容条件（需要至少2个条件）")
        return
    
    # 4. 手动销毁多余的服务器
    print(f"\n🗑️  开始手动缩容...")
    
    # 获取所有服务器列表
    try:
        servers_response = requests.get(f"{base_url}/api/v1/servers", timeout=10)
        if servers_response.status_code == 200:
            servers_data = servers_response.json()
            if servers_data.get("success"):
                servers_list = servers_data["data"]["servers"]
                print(f"  发现 {len(servers_list)} 个服务器")
                
                # 保留最小服务器数量，销毁多余的
                min_servers = scaling['scaling_config']['min_servers']
                servers_to_destroy = servers_list[min_servers:]
                
                print(f"  需要保留 {min_servers} 个服务器")
                print(f"  将销毁 {len(servers_to_destroy)} 个服务器")
                
                for i, server in enumerate(servers_to_destroy):
                    server_id = server["instance_id"]
                    print(f"  正在销毁服务器 {i+1}/{len(servers_to_destroy)}: {server_id}")
                    
                    try:
                        destroy_response = requests.delete(f"{base_url}/api/v1/servers/{server_id}", timeout=30)
                        if destroy_response.status_code == 200:
                            result = destroy_response.json()
                            if result.get("success"):
                                print(f"    ✅ 销毁成功: {server_id}")
                            else:
                                print(f"    ❌ 销毁失败: {result.get('error')}")
                        else:
                            print(f"    ❌ 销毁请求失败: {destroy_response.status_code}")
                    except Exception as e:
                        print(f"    ❌ 销毁异常: {e}")
                    
                    time.sleep(2)  # 等待销毁完成
                
                print(f"\n🎉 手动缩容完成！")
                
                # 5. 检查缩容后的状态
                time.sleep(5)
                print(f"\n📊 缩容后系统状态:")
                try:
                    response = requests.get(f"{base_url}/api/v1/system/status", timeout=10)
                    if response.status_code == 200:
                        data = response.json()
                        servers = data["data"]["servers"]["servers"]
                        print(f"  服务器数量: {servers['total']}")
                        print(f"  缩容成功！")
                    else:
                        print(f"❌ 获取状态失败: {response.status_code}")
                except Exception as e:
                    print(f"❌ 请求失败: {e}")
                    
            else:
                print(f"❌ 获取服务器列表失败: {servers_data.get('error')}")
        else:
            print(f"❌ 获取服务器列表请求失败: {servers_response.status_code}")
    except Exception as e:
        print(f"❌ 请求失败: {e}")

if __name__ == "__main__":
    manual_scale_in()
